package sdk

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

const (
	Webhook      = ""
	LocalWebHool = ""
)

type SendData struct {
	MsgType string `json:"msg_type"`
	Content string `json:"content"`
}

func SendMsg(msg string) {
	env := os.Getenv("ENV")
	var webhook string = Webhook
	if env == "" {
		env = "local"
	}
	if env == "local" || env == "test" || env == "dev" {
		webhook = LocalWebHool
	}
	msg = "【" + env + "】" + msg
	// json
	contentType := "application/json"
	// data

	content, _ := json.Marshal(struct {
		Text string `json:"text"`
	}{Text: msg})

	sendData, _ := json.Marshal(struct {
		MsgType string `json:"msg_type"`
		Content string `json:"content"`
	}{MsgType: "text", Content: string(content)})

	// sendData := `{
	// 	"msg_type": "text",
	// 	"content": s
	// }`

	// request
	result, err := http.Post(webhook, contentType, strings.NewReader(string(sendData)))
	if err != nil {
		fmt.Printf("post failed, err:%v", err)
		return
	}

	res := make(map[string]interface{})
	body, err := ioutil.ReadAll(result.Body)
	if err == nil {
		err = json.Unmarshal(body, &res)
		if err != nil || (res["code"] != 0 && res["msg"] != "success") {
			http.Post(webhook, contentType, strings.NewReader(`{"msg_type":"text", "content": {"text":"飞书消息发送失败，请尽快查看日志"}}`))
		}
	}
	defer result.Body.Close()
}
